<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

include_once(dirname(__FILE__).'/../../classes/AdminTab.php');
require_once(dirname(__FILE__).'/lib/zprofess/ZhelpdeskadminTab.php');

include_once(dirname(__FILE__).'/classes/ZdepartmentObject.php');

class ZadminGeneral extends ZhelpdeskadminTab
{
	/**
     * Sole constructor
    */ 
	public function  __construct()
	{
		global $cookie;
		
		$this->edit = false;
		$this->delete = false;
		$this->lang = true;
		$this->noLink = true;
		
		$this->table = 'zhelpdesk_department';
        $this->className = 'ZDepartmentObject';
        
        $this->_select = 'CONCAT_WS(" ", ze.`firstname`, ze.`lastname`) as namemod';
        $this->_join = 'LEFT JOIN `' . _DB_PREFIX_ . 'employee` as ze ON (ze.`id_employee` = a.`id_moderator`)';
        $this->fieldsDisplay = array(						
            'id_zhelpdesk_department' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25 ),
            'name' => array('title' => $this->l('Name'),'width' => 200 ,'align' => 'center', 'maxlength' => 250),
            'num_ticket' => array('title' => $this->l('Tickets'),'width' => 80 ,'align' => 'center'),
         	'ticket_open' => array('title' => $this->l('Ticket open'),'width' => 80 ,'align' => 'center'),
        	'ticket_close' => array('title' => $this->l('Ticket close'),'width' => 80 ,'align' => 'center'),
        	'ticket_pending' => array('title' => $this->l('Ticket pending'),'width' => 80 ,'align' => 'center'),
        	'ticket_missing' => array('title' => $this->l('Ticket missing'),'width' => 80 ,'align' => 'center'),
       	);
        
       	parent::__construct();
	}
	
	/**
	 * override: update num ticket, count status to _list
	 * 
	 * Get the current objects' list form the database
	 *
	 * @param integer $id_lang Language used for display
	 * @param string $orderBy ORDER BY clause
	 * @param string $_orderWay Order way (ASC, DESC)
	 * @param integer $start Offset in LIMIT clause
	 * @param integer $limit Row count in LIMIT clause
	 */
	public function getList($id_lang, $orderBy = NULL, $orderWay = NULL, $start = 0, $limit = NULL)
	{
		global $cookie;

		/* Manage default params values */
		if (empty($limit))
			$limit = ((!isset($cookie->{$this->table.'_pagination'})) ? $this->_pagination[1] : $limit = $cookie->{$this->table.'_pagination'});

		if (!Validate::isTableOrIdentifier($this->table))
			die (Tools::displayError('Table name is invalid:').' "'.$this->table.'"');

		if (empty($orderBy))
			$orderBy = $cookie->__get($this->table.'Orderby') ? $cookie->__get($this->table.'Orderby') : $this->_defaultOrderBy;
		if (empty($orderWay))
			$orderWay = $cookie->__get($this->table.'Orderway') ? $cookie->__get($this->table.'Orderway') : 'ASC';

		$limit = (int)(Tools::getValue('pagination', $limit));
		$cookie->{$this->table.'_pagination'} = $limit;

		/* Check params validity */
		if (!Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay)
			OR !is_numeric($start) OR !is_numeric($limit)
			OR !Validate::isUnsignedId($id_lang))
			die(Tools::displayError('get list params is not valid'));

		/* Determine offset from current page */
		if ((isset($_POST['submitFilter'.$this->table]) OR
		isset($_POST['submitFilter'.$this->table.'_x']) OR
		isset($_POST['submitFilter'.$this->table.'_y'])) AND
		!empty($_POST['submitFilter'.$this->table]) AND
		is_numeric($_POST['submitFilter'.$this->table]))
			$start = (int)($_POST['submitFilter'.$this->table] - 1) * $limit;

		/* Cache */
		$this->_lang = (int)($id_lang);
		$this->_orderBy = $orderBy;
		$this->_orderWay = Tools::strtoupper($orderWay);

		/* SQL table : orders, but class name is Order */
		$sqlTable = $this->table == 'order' ? 'orders' : $this->table;

		/* Query in order to get results with all fields */
		$sql = 'SELECT SQL_CALC_FOUND_ROWS
			'.($this->_tmpTableFilter ? ' * FROM (SELECT ' : '').'
			'.($this->lang ? 'b.*, ' : '').'a.*'.(isset($this->_select) ? ', '.$this->_select.' ' : '').'
			FROM `'._DB_PREFIX_.$sqlTable.'` a
			'.($this->lang ? 'LEFT JOIN `'._DB_PREFIX_.$this->table.'_lang` b ON (b.`'.$this->identifier.'` = a.`'.$this->identifier.'` AND b.`id_lang` = '.(int)($id_lang).')' : '').'
			'.(isset($this->_join) ? $this->_join.' ' : '').'
			WHERE 1 '.(isset($this->_where) ? $this->_where.' ' : '').($this->deleted ? 'AND a.`deleted` = 0 ' : '').(isset($this->_filter) ? $this->_filter : '').'
			'.(isset($this->_group) ? $this->_group.' ' : '').'
			'.((isset($this->_filterHaving) || isset($this->_having)) ? 'HAVING ' : '').(isset($this->_filterHaving) ? ltrim($this->_filterHaving, ' AND ') : '').(isset($this->_having) ? $this->_having.' ' : '').'
			ORDER BY '.(($orderBy == $this->identifier) ? 'a.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).
			($this->_tmpTableFilter ? ') tmpTable WHERE 1'.$this->_tmpTableFilter : '').'
			LIMIT '.(int)($start).','.(int)($limit);
		//$this->_list = Db::getInstance()->ExecuteS($sql);
		$_arrList = Db::getInstance()->ExecuteS($sql);
		foreach ($_arrList AS $key=>$value)
		{
			$sqlTicket = Db::getInstance()->getValue('
				SELECT SQL_CALC_FOUND_ROWS COUNT(`id_zhelpdesk_ticket`) as num_ticket 
				FROM `'._DB_PREFIX_.'zhelpdesk_ticket` a 
				WHERE a.`id_zhelpdesk_department` = '.$value['id_zhelpdesk_department'].'
			');
			$_arrList[$key]['num_ticket'] = $sqlTicket['num_ticket'];
			$_arrList[$key]['ticket_open'] = ZDepartmentObject::countStatusByDepartment((int)$value['id_zhelpdesk_department'], 1);
			$_arrList[$key]['ticket_close'] = ZDepartmentObject::countStatusByDepartment((int)$value['id_zhelpdesk_department'], 2);
			$_arrList[$key]['ticket_pending'] = ZDepartmentObject::countStatusByDepartment((int)$value['id_zhelpdesk_department'], 3);
			$_arrList[$key]['ticket_missing'] = ZDepartmentObject::countStatusByDepartment((int)$value['id_zhelpdesk_department'], 4);
		}
		$this->_list = $_arrList;
		$this->_listTotal = Db::getInstance()->getValue('SELECT FOUND_ROWS() AS `'._DB_PREFIX_.$this->table.'`');
	}
	
	/**
	 * Manage page display (form, list...)
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	function display()
	{
		echo '<h2>'.$this->l('General').'</h2>';
		parent::display();
	}
	
}